<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <crudOperation :permission="permission">
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="primary"
          :disabled="crud.selections.length === 0"
          @click="generateGifts"
        >
          生成赠品清单
        </el-button>

        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="primary"
          :disabled="crud.selections.length === 0"
          @click="generateBuyOrder"
        >
          生成采购单
        </el-button>
      </crudOperation>
      <div v-if="!crud.props.searchToggle">
        <el-form size="small" label-width="70px" v-formkey="{query:toQuery}">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="业务日期">
                <div class="flex flex-row">
                  <el-date-picker
                    v-model="query.startTime"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="开始日期"
                  />
                  <el-date-picker
                    v-model="query.endTime"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="结束日期"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="商品名称">
                <el-input v-model="query.goodsName" placeholder="请输入商品名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="往来单位">
                <zSelect :value.sync="query.customerId" :label="query.customerName"
                         url="api/dropDown/basCustomerList" style="width: 100%;"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="是否生成">
                <el-select v-model="query.isGenerate" class="filter-item" clearable placeholder="状态" size="small"
                           style="width: 100%;">
                  <el-option
                    v-for="item in dict.common_yes_or_no"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" align="center">
              <rrOperation :crud="crud"/>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <vue-context-menu :contextMenuData="contextMenuData"
                        @tableConfig="tableConfig"
                        @deletedata="deletedata"></vue-context-menu>
      <!-- 表格配置 -->
      <el-dialog title="表格配置"
                 :visible.sync="tableConfigShow"
                 width="60%">
        <j-table-column-config :columns.sync="crud.header"  @tabSave="tabSave" @pit="pit" />
      </el-dialog>

      <!--表格渲染-->
      <el-table ref="table"
                @row-click="crud.selectRow"
                :row-style="crud.rowClass"
                :row-class-name="crud.tableRowClassName"
                border
                v-loading="crud.loading"
                :data="crud.data"
                size="small"
                style="width: 100%;"
                v-if="isShowTable"
                @header-dragend="changeColWidth"
                @contextmenu.native="showMenu"
                @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55"/>
        <el-table-column type="index" width="60" label="序号"/>
<!--        <el-table-column-->
<!--          v-if="item.visible"-->
<!--          v-for="(item, index) in crud.header"-->
<!--          :key="`col_${index}`"-->
<!--          :prop="item.prop"-->
<!--          :label="columnLabel(item)"-->
<!--          :width="item.width + 'px'"-->
<!--          :data-porp='item.prop'-->
<!--          @contextmenu.native="showMenu"-->
<!--          @header-dragend="changeColWidth"-->
<!--        >-->
<!--          &lt;!&ndash; 自定义渲染模版 &ndash;&gt;-->
<!--          <template slot-scope="scope">-->
<!--            &lt;!&ndash; 当列key为 sort 时，渲染一个手柄icon &ndash;&gt;-->
<!--            <template v-if="item.prop =='sort'">-->
<!--              <div class="handle_move">-->
<!--                <i :class="scope.row['sort']" />-->
<!--              </div>-->
<!--            </template>-->
<!--            <template v-else>-->
<!--              <span v-if="item.type == 1" style="margin-left: 0px">{{scope.row[`${item.prop}`]}}</span>-->
<!--              <span v-if="item.type == 2" style="margin-left: 0px">{{ parseTime(scope.row[`${item.prop}`])}}</span>-->
<!--              <span v-if="item.type == 3" style="margin-left: 0px">{{ getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`) }}</span>-->
<!--            </template>-->
<!--          </template>-->
<!--        </el-table-column>-->

        <el-table-column width="120" v-if="columns.visible('busDate')" prop="busDate" label="业务日期"/>
        <el-table-column width="160" v-if="columns.visible('supplierName')" prop="supplierName" label="供应商名称"/>
        <el-table-column width="160" v-if="columns.visible('customerName')" prop="customerName" label="客户名称"/>
        <el-table-column width="160" v-if="columns.visible('goodsName')" prop="goodsName" label="商品名称"/>
        <el-table-column width="160" v-if="columns.visible('goodsCount')" prop="goodsCount" label="数量"/>
        <el-table-column width="160" v-if="columns.visible('boxCount')" prop="boxCount" label="箱数"/>
        <el-table-column width="160" v-if="columns.visible('sourceCode')" prop="sourceCode" label="来源合同编号"/>
        <el-table-column width="120" v-if="columns.visible('contractType')" prop="contractType" label="合同类型">
          <template slot-scope="scope">
            <span v-for="item in dict.t_fee_contract_type" v-if="item.value == scope.row.contractType">{{
                item.label
              }}</span>
          </template>
        </el-table-column>

       <el-table-column width="100" v-if="columns.visible('isGenerate')" prop="isGenerate" label="是否生成">
         <template slot-scope="scope">
           <span v-for="item in dict.common_yes_or_no" v-if="item.value == scope.row.isGenerate">{{
               item.label
             }}</span>
         </template>
       </el-table-column>
<!--        <el-table-column fixed="right" v-permission="['admin','feeContractGiftGoods:edit','feeContractGiftGoods:del']"-->
<!--                         label="操作"-->
<!--                         width="120" align="center">-->
<!--          <template slot-scope="scope">-->
<!--            <udOperation-->
<!--              :data="scope.row"-->
<!--              :permission="permission"-->
<!--            />-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
      <!--分页组件-->
      <pagination/>
    </div>
    <el-dialog title="生成赠品清单" :visible.sync="showGifgOrder" width="50%">
      <el-form size="small" ref="giftOrderForm" label-width="90px" :model="salesGiftListDto" :rules="rules">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="开始日期" prop="effectDate">
              <el-date-picker
                v-model="salesGiftListDto.effectDate"
                type="date"
                style="width: 100%;"
                format="yyyy - MM - dd "
                value-format="yyyy-MM-dd"
                default-value
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="截止日期" prop="cutOffDate">
              <el-date-picker
                v-model="salesGiftListDto.cutOffDate"
                type="date"
                style="width: 100%;"
                format="yyyy - MM - dd "
                value-format="yyyy-MM-dd"
                default-value
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="供应商" prop="supplierId">
              <zSelect :value.sync="salesGiftListDto.supplierId" :label="salesGiftListDto.supplierName"
                       url="api/dropDown/basCustomerList"
                       :params="{isContact:'1,2'}"
                       style="width:  100%"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="商贸公司" prop="fcustomerId">
              <zSelect :value.sync="salesGiftListDto.fcustomerId" url="api/dropDown/basCustomerList" :params="{type:2}"
                       style="width:  100%;"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="赠品类型" prop="giftType">
              <el-select v-model="salesGiftListDto.giftType" class="filter-item" clearable placeholder="赠品类型"
                         size="small"
                         style="width: 100%;">
                <el-option
                  v-for="item in dict.t_sales_gift_list_gift_type"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="商品类型" prop="goodsTagId">
              <zSelect :value.sync="salesGiftListDto.goodsTagId" url="api/dropDown/basGoodsTagList" clearable
                       placeholder="商品类型" style="width:  100%;" @change="changeGoodsType"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="showGifgOrder = false">取消</el-button>
        <el-button :loading="confirmGiftloading" type="primary" @click="confirmGift">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crudFeeContractGiftGoods from '@/api/erp/feeContractGiftGoods'
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import {Notification} from "element-ui";

import {publicListKey} from "@/utils/key";
import {tablemixins} from "@/mixins/tablemixins";
import jTableColumnConfig from "@/components/jTableColumnConfig/jTableColumnConfig";

// crud交由presenter持有
const defaultCrud = CRUD({
  title: '费用合同赠品',
  url: 'api/feeContractGiftGoods',
  sort: 'id,desc',
  optShow: {
    add: false,
    edit: false,
    del: true,
    copy: false,
    leadingIn: false,
    download: false,
    downloadDetail: false,
    isColumn: false,
    print: false, // 打印
    printDetail: false, // 打印详情
    enable: false,
    disable: false,
    pass: false,
    reject: false
  },
  crudMethod: {...crudFeeContractGiftGoods}
})
const defaultForm = {
  id: null,
  busDate: null,
  contractType: null,
  sourceType: null,
  sourceId: null,
  sourceCode: null,
  supplierId: null,
  supplierCode: null,
  supplierName: null,
  customerId: null,
  customerCode: null,
  customerName: null,
  fCustomerId: null,
  fCustomerCode: null,
  fCustomerName: null,
  deptId: null,
  deptCode: null,
  deptName: null,
  userId: null,
  userCode: null,
  userName: null,
  isGenerate: null,
  goodsId: null,
  goodsCode: null,
  goodsName: null,
  barcode: null,
  boxBarcode: null,
  helpSign: null,
  model: null,
  goodsTagId: null,
  goodsTagCode: null,
  goodsTagName: null,
  goodsCount: null,
  boxCount: null,
  giftType: null,
  effectDate: null,
  cutOffDate: null,
  seq: null,
  remark: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null
}
export default {
  name: 'FeeContractGiftGoods',
  components: {pagination, crudOperation, rrOperation, udOperation,jTableColumnConfig},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud(),publicListKey,tablemixins],
  dicts: ['t_fee_contract_type', 'common_yes_or_no', 't_bas_goods_type', 't_sales_gift_list_gift_type'],
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      permission: {
        add: ['admin', 'feeContractGiftGoods:add'],
        edit: ['admin', 'feeContractGiftGoods:edit'],
        del: ['admin', 'feeContractGiftGoods:del'],
        import: ['admin', 'feeContractGiftGoods:import'],
        export: ['admin', 'feeContractGiftGoods:export'],
        copy: ['admin', 'feeContractGiftGoods:copy'],
        upload: ['admin', 'feeContractGiftGoods:upload'],
        download: ['admin', 'feeContractGiftGoods:download'],
      },
      rules: {
        effectDate: [
          {required: true, message: '开始日期不能为空', trigger: 'blur'}
        ],
        cutOffDate: [
          {required: true, message: '截止日期不能为空', trigger: 'blur'}
        ],
        supplierId: [
          {required: true, message: '供应商不能为空', trigger: 'blur'}
        ],
        fcustomerId: [
          {required: true, message: '商贸公司不能为空', trigger: 'blur'}
        ],
        giftType: [
          {required: true, message: '赠品类型不能为空', trigger: 'blur'}
        ],
        goodsTagId: [
          {required: true, message: '赠品类型不能为空', trigger: 'blur'}
        ],
      },
      showGifgOrder: false,
      confirmGiftloading: false,
      salesGiftListDto: {},
    }
  },
  watch: {},
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    generateGifts() {
      //生成赠品清单
      let generatedIndexs = []
      let saleIndexs = []
      for (let i = 0; i < this.crud.selections.length; i++) {
        const row = this.crud.selections[i]
        console.log(row.contractType)
        if (row.contractType == 1) {
          saleIndexs.push(i + 1)
        }
        if (row.isGenerate == 1) {
          generatedIndexs.push(i + 1)
        }
      }
      if (saleIndexs.length > 0) {
        Notification.error({title: "第" + saleIndexs.join(",") + "行，采购单不能生成赠品"})
        return
      }
      if (generatedIndexs.length > 0) {
        Notification.error({title: "第" + generatedIndexs.join(",") + "行，已生成的赠品单不能再次生成"})
        return
      }
      this.showGifgOrder = true
    },
    generateBuyOrder() {
      let generatedIndexs = []
      let saleIndexs = []
      for (let i = 0; i < this.crud.selections.length; i++) {
        const row = this.crud.selections[i]
        if (row.contractType == 2) {
          saleIndexs.push(i + 1)
        }
        if (row.isGenerate == 1) {
          generatedIndexs.push(i + 1)
        }
      }
      if (saleIndexs.length > 0) {
        Notification.error({title: "第" + saleIndexs.join(",") + "行，销售单不能生成采购单"})
        return
      }
      if (generatedIndexs.length > 0) {
        Notification.error({title: "第" + generatedIndexs.join(",") + "行，已生成的采购单不能再次生成"})
        return
      }
      //生成采购单
      this.$confirm('是否确认生成采购单?', '确认信息', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        const params = {
          content: this.crud.selections
        }
        crudFeeContractGiftGoods.addBuyOrder(params).then(res => {
          if (res.success) {
            this.crud.refresh()
            this.$message.success("生成成功")
          } else {
            this.$message.error("生成失败")
          }
        })
      }).catch(() => {
        this.$message.error("生成失败")
      });
    },
    confirmGift() {
      this.$refs['giftOrderForm'].validate(valid => {
        if (!valid) {
          return
        }
        this.confirmGiftloading = true
        const params = {
          salesGiftListDto: this.salesGiftListDto,
          content: this.crud.selections
        }
        crudFeeContractGiftGoods.addSalesGiftList(params).then(res => {
          if (res.success) {
            this.showGifgOrder = false
            this.confirmGiftloading = false
            this.crud.refresh()
            this.$message.success("生成成功")
          } else {
            this.confirmGiftloading = false
            this.$message.error("生成失败")
          }
        }).catch(e => {
          this.confirmGiftloading = false
          this.$message.error("生成失败")
        })
      });
    },
    getValue(e) {
      this.query.startTime = this.query.dataExtent[0]
      this.query.endTime = this.query.dataExtent[1]
    },
    changeGoodsType(e){
      console.log(e)
      this.salesGiftListDto.goodsTagId = e.id
      this.salesGiftListDto.goodsTagCode = e.code
      this.salesGiftListDto.goodsTagName = e.name
    }
  }
}
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
</style>
